package logic

import (
	"book-hub/cache"
	"book-hub/models"
	"book-hub/pkg"
	"context"
	"fmt"

	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NewPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNewPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NewPasswordLogic {
	return &NewPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NewPasswordLogic) NewPassword(in *bookrpc.NewPasswordRequest) (*bookrpc.NewPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	models.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当然账号未注册")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sensms"+in.Mobile).Result()
	if result != in.SenSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	if user.Password == pkg.Md5str(in.Password) {
		return nil, fmt.Errorf("新密码与原密码一致")
	}
	if in.Password != in.NewPassword {
		return nil, fmt.Errorf("确认密码与新密码不一致")
	}
	user.Password = pkg.Md5str(in.Password)
	models.DB.Updates(&user)
	return &bookrpc.NewPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
